package com.example.jwtlearning.utils;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: anlu
 * @Date: 2021/08/09
 * @Description:
 */
public class JWTUtils {

    /*
     * 加密秘钥
     * */
    private static String SECRET_BASE64_KEY = "LX2lnm1cyaHUuPHWxb02Txzl5yTx2lqfRthIFrHO+zQ=" ;


    /**
     * 生成签名的时候使用的秘钥.
     * 注意：切记这个秘钥不能外露哦。它就是你服务端的私钥，在任何场景都不应该流露出去。一旦客户端得知这个secret, 那就意味着客户端是可以自我签发jwt了。
     */
    public static SecretKey generalKey() {
        byte[] encodedKey = java.util.Base64.getDecoder().decode(SECRET_BASE64_KEY);
        return new SecretKeySpec(encodedKey, SignatureAlgorithm.HS256.getJcaName());
    }

    public static String createJWT(String id, String subject, long ttlMillis, SecretKey key){
        //获取签名算法
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        JwtBuilder builder = Jwts.builder()
                .setId(id)
                .setSubject(subject)
                .setIssuer("user")
                .setIssuedAt(now)
                .signWith(key,signatureAlgorithm);
        if(ttlMillis >= 0){
            long expMillis = nowMillis + ttlMillis;
            Date expDate = new Date(expMillis);
            //设置过期时间
            builder.setExpiration(expDate);
        }
        return builder.compact();

    }


    public static Claims parseJWT(String jwt, SecretKey keySpec){
        return Jwts.parser()
                .setSigningKey(keySpec)
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static Claims parseJWT(String jwt){
        return Jwts.parser()
                .setSigningKey(generalKey())
                .parseClaimsJws(jwt)
                .getBody();
    }

    public static ResultCode validateJWT(String jwt){
        ResultCode checkResult = new ResultCode();
        Claims claims = null;
        try {
            claims = parseJWT(jwt);
            checkResult.setSuccess(true);
            checkResult.setClaims(claims);
        } catch (ExpiredJwtException e) {
            checkResult.setErrCode("解析失败");
            checkResult.setSuccess(false);
        }
        return checkResult;
    }
    public static void main(String[] args) {
        //生成密匙
//        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        SecretKey key = generalKey();
        String jwt = JWTUtils.createJWT("1","test",10000*60,key);
        System.out.println(jwt);
        System.out.println(JWTUtils.parseJWT(jwt,key));
    }
}
